var mysql = require('mysql')
var qiniu = require('qiniu')
//连接mysql
var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'xhkcwechat'
});
connection.connect();

//调用数据库方法  不带参数
var conNoArgs = function (sql) {
    return new Promise(function (resolve, reject) {
        connection.query(sql, function (error, result) {
            if (error) {
                console.log(error);
                // reject(error);
            }
            if (result) {
                resolve(result);
            }
        })
    });
}
var getOpenid = function (request, url_2) {
    return new Promise(function (resolve, reject) {
        request(url_2, function (error, res, body) {
            //3.出现错误后直接返回, 如果没出现错误说明数据获取成功
            if (error) {
                console.log(error);
                // reject(error);
                return;
            } else {
                //3.1 请求正确获取用户的session_key和openid
                //{"session_key":"VprmFTBgIyVWfjSxN4F1+w==","openid":"oj5Ft5dCyN2-N914WgsrIA61AuMA"}
                resolve(JSON.parse(body));
            }

        })
    });
}
//调用数据库方法  带参数
var con = function (sql, params) {
    return new Promise(function (resolve, reject) {
        connection.query(sql, params, function (error, result) {
            if (error) {
                console.log(error);
                reject(error);
            }
            if (result) {
                resolve(result);
            }
        })
    });
}

//上传图片
var uploadpic = function (uptoken, key, localFile) {
    return new Promise(function (resolve, reject) {
        // var extra = new qiniu.io.PutExtra();
        var extra = new qiniu.form_up.PutExtra();
        const formUploader = new qiniu.form_up.FormUploader(config)
        formUploader.putFile(uptoken, key, localFile, extra, function(err, res) {
            if(!err) {
                // 上传成功， 处理返回值
                console.log(res.hash, res.key, res.persistentId);
                resolve(res)
            } else {
                // 上传失败， 处理返回代码
                console.log(err);
                reject(err)
            }
        });
    });
}



module.exports={getOpenid,conNoArgs,con,uploadpic}
